package com.gaff.emp.core.modules.auth.resolver;

import com.gaff.emp.core.modules.auth.LoginUserInfo;
import com.gaff.emp.core.modules.auth.annotation.LoginUser;
import com.gaff.emp.core.modules.auth.interceptor.AuthorizationInterceptor;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;


@Component
public class UserInfoHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(LoginUserInfo.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) {
        Object userInfo = request.getAttribute(AuthorizationInterceptor.USER_INFO_KEY, RequestAttributes.SCOPE_REQUEST);
        return userInfo;
    }
}
